package server;

import util.FileConvert;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.UUID;

/**
 * User: tum0r
 * Package Name: server
 * Time: 2019-03-16 Saturday 15:38:28
 */
public class FileServer extends BaseServer {

    public String checkFile(String hex) {
        StringBuilder result = new StringBuilder();
        LinkedList<LinkedHashMap<String, Object>> temp = sql.query("select uuid from file where content=?", new Object[]{hex});
        if (temp!=null&&temp.size() != 0) {
            result.append(temp.get(0).get("uuid").toString());
        }
        return result.toString();
    }

    public String saveFile(File file) {
        StringBuilder result = new StringBuilder();
        FileConvert convert = new FileConvert();
        try {
            String hex = convert.fileToHex(file);
            String id = checkFile(hex);
            if(id.equals("")){
                result.append(UUID.randomUUID().toString());
                sql.update("insert into file values(?, ?, ?, ?)", new Object[]{result.toString(), file.getName(), convert.getFileHash(hex), hex});
            }else{
                result.append(id);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public File getFile(String uuid) {
        File result = null;
        LinkedList<LinkedHashMap<String, Object>> temp = sql.query("select * from file where uuid=?", new Object[]{uuid});
        if (temp.size() != 0) {
            String hex = temp.get(0).get("content").toString();
            FileConvert convert = new FileConvert();
            try {
                result = convert.hexToFile(hex);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public String getImage(String uuid){
        StringBuilder result = new StringBuilder();
        LinkedList<LinkedHashMap<String, Object>> temp = sql.query("select * from file where uuid=?", new Object[]{uuid});
        if (temp.size() != 0) {
            String hex = temp.get(0).get("content").toString();
            FileConvert convert = new FileConvert();
            result.append(convert.hexToBase64(hex));
        }
        return result.toString();
    }
}
